package cn.wowjoy.office.materialmanage.materiallist;

import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.MaterialListAdapter;
import cn.wowjoy.office.common.adapter.MenuAdapter;
import cn.wowjoy.office.common.widget.EngineActionSheet;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.GoodsDetailRequest;
import cn.wowjoy.office.data.response.GoodsDetailResponse;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Sherily on 2017/11/1.
 */

public class MaterialListViewModel extends NewBaseViewModel {

    @Inject
    ApiService apiService;

    @Inject
    PreferenceManager preferenceManager;

    MediatorLiveData<LiveDataWrapper<List<GoodsDetailResponse>>>  goodsListLiveData = new MediatorLiveData<>();
    MediatorLiveData<GoodsDetailResponse>  goodsDetail = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<ResultEmpty>>  startStop = new MediatorLiveData<>();
    MediatorLiveData<PopuModel>  meun = new MediatorLiveData<>();
    @Inject
    public MaterialListViewModel(@NonNull NewMainApplication application) {
        super(application);
        materialListAdapter.setmItemEventHandler(this);
        menuAdapter.setmEventListener(this);
    }

    @Override
    public void onCreateViewModel() {

    }

    public MaterialListAdapter materialListAdapter = new MaterialListAdapter();
    public LRecyclerViewAdapter adapter = new LRecyclerViewAdapter(materialListAdapter);

    public MenuAdapter menuAdapter = new MenuAdapter();
    private EngineActionSheet actionSheet;

    private List<GoodsDetailResponse> datas = new ArrayList<>();

    public MediatorLiveData<PopuModel> getMeun() {
        return meun;
    }

    public void setData(boolean isRefresh, List<GoodsDetailResponse> data) {
        if (isRefresh) {
           materialListAdapter.refresh(data);
        } else {
            materialListAdapter.loadMore(data);
        }
        adapter.removeFooterView();
        if (!isRefresh && (null == data || data.isEmpty() )){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
//            NodataFootviewBinding binding = DataBindingUtil.inflate(inflater, R.layout.nodata_footview,null,false);
            adapter.addFooterView(view);

//            adapter.getFooterView().setForegroundGravity(Gravity.CENTER);
//            materialListActivity.getBinding().recyclerView.setNoMore(true);

        }
//        materialListAdapter.notifyDataSetChanged();
        adapter.notifyDataSetChanged();
        refreshComplete();
    }


    private String toastStr = "";
    public void showActionSheet(int position){
        String title = "";
        String btn = "";
        String toastStr = "";
        if (position%2 == 0){
            btn = "启用";
            title = "启用后，該物资将恢复申领、入库和出库。";
            toastStr = "启用成功";

        } else {
            btn = "停用";
            title = "停用后，該物资将无法申领、入库和出库。";
            toastStr = "停用成功";

        }
        String finalToastStr = toastStr;
        actionSheet = new EngineActionSheet.Builder()
                .showTitle(true)
                .setTitle(title,null,false)
                .setBtn(btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.toastImage(getApplication(), finalToastStr,-1);
                        actionSheet.dismiss();
                    }
                })
                .setCancel("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        actionSheet.dismiss();
                    }
                })
                .create();
        actionSheet.show(getApplication());
    }

    private final int pageSize = 10;
    private int pageIndex = 0;

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        getGoodsListInfo(isStop,key,ref);
    }

    private String key;
    private String isStop;

    private boolean isFirst = true;
    private MDialog waitDialog;

    public MediatorLiveData<LiveDataWrapper<List<GoodsDetailResponse>>> getGoodsListLiveData() {
        return goodsListLiveData;
    }

    public MediatorLiveData<GoodsDetailResponse> getGoodsDetail() {
        return goodsDetail;
    }

    public MediatorLiveData<LiveDataWrapper<ResultEmpty>> getStartStop() {
        return startStop;
    }

    public void startGoogs(String code){
       startStop.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.startGoods(new GoodsDetailRequest(code))
                .flatMap(new ResultDataParse<ResultEmpty>())
                .compose(new RxSchedulerTransformer<ResultEmpty>())
                .subscribe(new Consumer<ResultEmpty>() {
                               @Override
                               public void accept(ResultEmpty resultEmpty) throws Exception {
                                   startStop.setValue(LiveDataWrapper.success(resultEmpty));
                                   ToastUtil.toastImage(getApplication().getApplicationContext(),"启用成功",-1);
//                                   getGoodsListInfo(isStop,key,true);
//                                   materialListActivity.refreshRV();
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                startStop.setValue(LiveDataWrapper.error(throwable,null));


                            }
                        });
        addDisposable(disposable);

    }

    public  void stopGoods(String code){
        startStop.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.stopGoods(new GoodsDetailRequest(code))
                .flatMap(new ResultDataParse<ResultEmpty>())
                .compose(new RxSchedulerTransformer<ResultEmpty>())
                .subscribe(new Consumer<ResultEmpty>() {
                               @Override
                               public void accept(ResultEmpty resultEmpty) throws Exception {
                                   startStop.setValue(LiveDataWrapper.success(resultEmpty));
                                   ToastUtil.toastImage(getApplication().getApplicationContext(),"停用成功",-1);
//                                   getGoodsListInfo(isStop,key,true);
//                                   materialListActivity.refreshRV();

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                startStop.setValue(LiveDataWrapper.error(throwable,null));


                            }
                        });
        addDisposable(disposable);

    }
    public void getGoodsListInfo(String isStop,String key,boolean isRefresh){

        this.key = key;
        this.isStop = isStop;
        if (isRefresh){
            pageIndex = 0;
        } else {
            ++pageIndex;
        }
        goodsListLiveData.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getGoodsListInfo(isStop,key,pageIndex,pageSize)
                .flatMap(new ResultDataParse<List<GoodsDetailResponse>>())
                .compose(new RxSchedulerTransformer<List<GoodsDetailResponse>>())
                .subscribe(new Consumer<List<GoodsDetailResponse>>() {
                               @Override
                               public void accept(List<GoodsDetailResponse> goodsResponse) throws Exception {

                                   goodsListLiveData.setValue(LiveDataWrapper.success(goodsResponse));
                                   materialListAdapter.setmToken(preferenceManager.getHeaderToken());
                                   setData(isRefresh, goodsResponse);

                                   if (!TextUtils.isEmpty(key)) {
                                      materialListAdapter.setKeyWord(key);
                                   } else {
                                       materialListAdapter.setKeyWord("");
                                   }

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                               goodsListLiveData.setValue(LiveDataWrapper.error(throwable,null));

                            }
                        });
        addDisposable(disposable);

    }

    public void handler(GoodsDetailResponse response){

        if (response.stopStatus()){
            startGoogs(response.getGoodsCode());

        } else {
            stopGoods(response.getGoodsCode());
        }

    }
    private List<PopuModel> popuModels;

    public void createMeun(){
        if (null == popuModels)
            popuModels = new ArrayList<>();
        if (popuModels.isEmpty()){
            popuModels.add(new PopuModel("全部",true,""));
            popuModels.add(new PopuModel("已启用",false,"n"));
            popuModels.add(new PopuModel("已停用",false,"y"));
        }
       menuAdapter.setPopuModels(popuModels);
    }


    public void jump(GoodsDetailResponse response){
        goodsDetail.setValue(response);
    }



    public void sort(PopuModel popuModel){
        meun.setValue(popuModel);
    }

}
